const lib_configurg = {
    loading_time_out: 15000,//15秒 loading等待时间，超过此时间将自动取消loading
}
var menuInit =[];//初始化菜单

/********异步提交函数**************************/
//form支持多表单提交，中间用,隔开，url为提交地址
function subForm(form, url, callback = null) {
    //防止高频点击
    var date = new Date();
    var time = date.getTime(); //毫秒时间戳
    let finger = 2;
    if (typeof minTime == "undefined") {
        minTime = time + 2000; //下次点击的最小时间
    } else {
        if (minTime && time < minTime) {
            finger = 1;
            warn("操作过于频繁");
            //console.log("time:" + time + "，mintime:" + minTime + "，差额：" + (time - minTime));
        } else {
            finger = 2;
            minTime = time + 2000; //下次点击的最小时间
        }
    }

    if (finger === 2) {
        let con = setTimeout(function () {
            $("#loading", window.top.document).hide();
        }, lib_configurg.loading_time_out);
        $("#loading", window.top.document).show();
        //串联表单
        var formName = form.split(",");
        var forms = [];
        for (var i = 0; i < formName.length; i++) {
            if (formName[i] !== "") {
                forms = forms.concat($("[name=" + formName[i] + "]"));
            }
        }
        var obj = event.target;//发生点击事件的当前html节点
        var jsonData = getFormJson(forms);
        //异步提交数据
        $.post(url, {serialize_json: JSON.stringify(jsonData)}, function (data) {
            $("#loading", window.top.document).hide();
            clearTimeout(con);
            data.obj = obj;//发生点击事件的当前html节点
            data.isIframe = window.top !== window.self
            data.currentIframe = window.frameElement; // 当前 iframe
            if ((data.warn === 2 || data.warn === '2') && callback && $.isFunction(callback)) {
                //如果存在回调函数
                callback(data);
            }else {
                returnProcess(data)
            }
        }, "json");
    }
}

/******************返回值处理*****************/
function returnProcess(data) {
    if (data.warn === 2 || data.warn === '2') {
        var parentIframe = data.currentIframe ? data.currentIframe.ownerDocument.defaultView.frameElement : null; // 获取父级 iframe
        if(data.script){
            //$json['script'] = "<script>reloadTemplateOption('$info[menuFour]')</script>";
            const parser = new DOMParser();
            const parsedDocument = parser.parseFromString(data.script, 'text/html');
            const scriptElement = parsedDocument.querySelector('script');
            if (scriptElement) {
                const scriptTag = document.createElement('script');
                scriptTag.text = scriptElement.text;
                document.body.appendChild(scriptTag);
            }
            if (data.msg) {
                parentIframe.warn(data.msg);
            }
        } else {
            //弹窗处理
            if($(data.obj).parents("[layerId]").length === 1){
                //弹窗下一步进入详情页的情况
                if(data.iframe){
                    return newIframe(data.iframeName, data.iframe)
                }
                //如果是列表页，则保留查询条件和分页
                if ($(data.obj).parents("[searchFormId]").length === 1) {
                    //获取查询结果区域的ID号
                    var searchFormId = $(data.obj).parents("[searchFormId]").attr("searchFormId");
                    //更新查询结果
                    var pageNow = $("[searchformhtml=" + searchFormId + "] .pageButton .pageNow");//当前页
                    if (pageNow.length === 1) {//如果存在分页
                        pageNow.click();
                    } else {
                        $("[searchformhtml=" + searchFormId + "]").find("input[type=submit]").click();
                    }
                    //关闭当前编辑弹窗
                    $(data.obj).parents(".win").find(".winClose").click();
                    if (data.msg) {
                        warn(data.msg, 'error');
                    }
                    if ($.cookie('warn')) {
                        warn($.cookie('warn'));
                        $.cookie('warn', '');
                    }
                    // 在这里执行需要等待异步请求结束后的代码，函数将会被执行一次，之后就会被销毁
                    $(document).one('ajaxStop', function () {
                        initScrollPosition();
                    });
                } else if (data.href) {
                    //如果异步返回的json参数中定义了重定向url，则跳转到本url
                    if (data.isIframe) {
                        $(data.currentIframe).attr("src", data.href);
                    }else{
                        window.location.href = data.href;
                    }
                } else if ($("#renovate").attr("url")) {
                    //页卡切换时会保存菜单关键字在renovate的url中
                    if (data.isIframe) {
                        $(data.currentIframe).attr("src", $("#renovate").attr("url"));
                    }else{
                        window.location.href = $("#renovate").attr("url");
                    }
                } else {
                    window.location.reload();
                }
            } else{
                //先判断返回的链接是否等于父级 iframe。是的话则关闭当前 iframe，不是则更新当前 iframe
                if (parentIframe && $(parentIframe).attr("src") === data.href) {
                    $(parentIframe).attr("src", $(parentIframe).attr("src"));
                    //关闭操作页
                    $(data.currentIframe).attr("src", "")
                    $(data.currentIframe).parent().css("display", "none").empty()
                } else if (data.href) {
                    //如果异步返回的json参数中定义了重定向url，则跳转到本url
                    if (data.isIframe) {
                        $(data.currentIframe).attr("src", data.href);
                    }else{
                        window.location.href = data.href;
                    }
                } else if ($("#renovate").attr("url")) {
                    //页卡切换时会保存菜单关键字在renovate的url中
                    if (data.isIframe) {
                        $(data.currentIframe).attr("src", $("#renovate").attr("url"));
                    }else{
                        window.location.href = $("#renovate").attr("url");
                    }
                } else {
                    window.location.reload();
                }
            }
        }
    } else {
        warn(data.warn, 'error');
        // 刷新验证码
        if(data.warn === "验证码输入错误"){
            $("#checkNumImg").click();
        }
    }

}

/******************组合表单数据*****************/
function getFormJson(forms) {
    const data = {};
    forms.forEach((form) => {
        const formData = new FormData(form[0]);
        for (const [key, value] of formData.entries()) {
            // 处理数组
            if (key.endsWith('[]')) {
                const arrayKey = key.slice(0, -2);
                // 如果键名中含有数组标记，例如 "position[abc][csc][]"
                if (/\[\]$/.test(key)) {
                    const objKeys = key.split(/\[|\]/).filter(Boolean);
                    let target = data;
                    objKeys.forEach((key, index) => {
                        if (index === objKeys.length - 1) {
                            if (!target[key]) {
                                target[key] = [];
                            }
                            target[key].push(value);
                        } else {
                            if (!target[key]) {
                                target[key] = isNaN(objKeys[index + 1]) ? {} : [];
                            }
                            target = target[key];
                        }
                    });
                }
                // 如果键名中不含有数组标记，例如 "hobbies[]"
                else {
                    if (!data[arrayKey]) {
                        data[arrayKey] = [];
                    }
                    data[arrayKey].push(value);
                }
            }
            // 处理对象
            else if (key.includes('[')) {
                const keys = key.split(/\[|\]/).filter(Boolean);
                let target = data;
                keys.forEach((key, index) => {
                    if (index === keys.length - 1) {
                        target[key] = value;
                    } else {
                        if (!target[key]) {
                            target[key] = isNaN(keys[index + 1]) ? {} : [];
                        }
                        target = target[key];
                    }
                });
            }
            // 处理普通值
            else {
                data[key] = value;
            }
        }
    });
    return data;
}


/******************警示弹出层*****************/
function warn(warn, type = 'info') {
    msg(warn, type);
    // $("#warn").show();
    // $("#warnWord").html(warn);
}

/*根据省份选择城市*/
function regionProvince(obj) {
    //参数准备
    var formName = $(obj).parents("form").attr("name");
    var provinceValue = $(obj).val();
    var city = $(obj).next("select");
    var area = $(city).next("select");
    //异步获取城市
    $.post(root + "library/libData.html?type=getCity", {
        province: provinceValue
    }, function (data) {
        city.html(data.city);
    }, "json");
    //初始化区域
    area.html("<option value=''>--区域--</option>");
}

/*根据城市选择区域*/
function regionCity(obj) {
    //参数准备
    var formName = $(obj).parents("form").attr("name");
    var provinceValue = $(obj).prev("select").val();
    var cityValue = $(obj).val();
    var area = $(obj).next("select");
    //异步获取区域
    $.post(root + "library/libData.html?type=getArea", {
        province: provinceValue,
        city: cityValue
    }, function (data) {
        area.html(data.area);
    }, "json");
}

/*******获取本地路径*****************/
//sourceId：文件域ID号
function getFileUrl(sourceId) {
    var url;
    if (navigator.userAgent.indexOf("MSIE") >= 1) { // IE
        url = document.getElementById(sourceId).value;
    } else if (navigator.userAgent.indexOf("Firefox") > 0) { // Firefox
        url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
    } else if (navigator.userAgent.indexOf("Chrome") > 0) { // Chrome
        url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
    } else {
        url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
    }
    return url;
}

/*******获取短信验证码*****************/
function newProve(tel) {
    $.post(root + "library/libData.html?type=newProve", {
        tel: tel
    }, function (data) {
        warn(data.warn);
    }, "json");
}

/*******跳转*****************/
function href(url) {
    window.location.href = url.includes(root) ? url : root + url;
    return false;
}

/*弹出层移动函数*/
function move(id) {
    //参数初始化
    var win = $("#" + id).children(".win"); //需要移动的弹出层窗口
    var title = $("#" + id).find(".winTitle"); //点击区域
    //鼠标按下
    title.mousedown(function (e) {
        var ev = e || event;
        var startX = ev.clientX;
        var startY = ev.clientY;
        var left = parseInt(win.css("margin-left"));
        var top = parseInt(win.css("margin-top"));
        document.onmousemove = function (m) {
            var mv = m || event;
            var endX = mv.clientX;
            var endY = mv.clientY;
            var moveX = endX - startX;
            var moveY = endY - startY;
            //计算值
            winLeft = (left + moveX) + "px";
            winTop = (top + moveY) + "px";
            //移动弹窗
            win.css({
                "margin-top": winTop,
                "margin-left": winLeft
            });
        }
        document.onmouseup = function () {
            document.onmousemove = null;
            document.onmouseup = null;
        }
    })
};
(function ($) {
    var val = '关键字';
    $.fn.fSelect = function (options) {
        var settings = '';
        if (typeof options == 'string') {
            settings = options;
        } else {
            settings = $.extend({
                placeholder: '关键字',
                numDisplayed: 15,
                overflowText: '{n} selected',
                searchText: '关键字',
                showSearch: true
            }, options);
        }

        /**
         * Constructor
         */
        function fSelect(select, settings) {
            this.$select = $(select);
            this.settings = settings;
            this.create();
        }

        /**
         * Prototype class
         */
        fSelect.prototype = {
            create: function () {
                var multiple = this.$select.is('[multiple]') ? ' multiple' : '';
                var addStyle = this.settings.class ? ' ' + this.settings.class : '';
                this.$select.wrap('<div class="fs-wrap' + multiple + addStyle + '"></div>');
                val = this.$select.attr('title');
                this.$select.before('<div class="fs-label-wrap"><div class="fs-label">' + val + '</div><span class="fs-arrow"></span></div>');
                this.$select.before('<div class="fs-dropdown hidden"><div class="fs-options"></div></div>');
                this.$select.addClass('hidden');
                this.$wrap = this.$select.closest('.fs-wrap');
                //设置跟父级元素fs-wrap一样的宽度
                var obj = this.$select
                setTimeout(function() {
                    obj.parent().find(".fs-dropdown").width(obj.parent().outerWidth());
                }, 100);
                this.reload();
            },
            reload: function () {
                if (this.settings.showSearch) {
                    var search = '<div class="fs-search"><input type="search" placeholder="' + this.settings.searchText + '" /></div>';
                    this.$wrap.find('.fs-dropdown').prepend(search);
                }
                var choices = this.buildOptions(this.$select);
                this.$wrap.find('.fs-options').html(choices);
                this.reloadDropdownLabel('reload');
            },
            destroy: function () {
                this.$wrap.find('.fs-label-wrap').remove();
                this.$wrap.find('.fs-dropdown').remove();
                this.$select.unwrap().removeClass('hidden');
            },
            buildOptions: function ($element) {
                var $this = this;
                var choices = '';
                $element.children().each(function (i, el) {
                    var $el = $(el);
                    if ('optgroup' == $el.prop('nodeName').toLowerCase()) {
                        choices += '<div class="fs-optgroup">';
                        choices += '<div class="fs-optgroup-label">' + $el.prop('label') + '</div>';
                        choices += $this.buildOptions($el);
                        choices += '</div>';
                    } else {
                        var selected = $el.is('[selected]') ? ' selected' : '';
                        if (!$el.prop('value') && $el.html().indexOf("-") !== -1) {
                            choices += '<div class="fs-option fs-option-no ' + selected + '" data-value=""><div title="' + $el.html() + '" class="fs-option-label">' + $el.html() + '</div></div>';
                        } else {
                            choices += '<div class="fs-option' + selected + '" data-value="' + $el.prop('value') + '"><span class="fs-checkbox"><i></i></span><div title="' + $el.html() + '" class="fs-option-label">' + $el.html() + '</div></div>';
                        }
                    }
                });
                return choices;
            },
            reloadDropdownLabel: function (source = '') {
                var settings = this.settings;
                var labelText = [];
                this.$wrap.find('.fs-option.selected').each(function (i, el) {
                    labelText.push($(el).find('.fs-option-label').text());
                });
                if (labelText.length < 1) {
                    //labelText = settings.placeholder;
                    labelText = val;
                } else if (labelText.length > settings.numDisplayed) {
                    labelText = settings.overflowText.replace('{n}', labelText.length);
                } else {
                    labelText = labelText.join(', ');
                }
                this.$wrap.find('.fs-label').html(labelText);
                this.$wrap.find('.fs-label').attr('title', labelText);
                if (source !== 'reload') {
                    this.$select.change();
                }
            }
        }
        /**
         * Loop through each matching element
         */
        return this.each(function () {
            var data = $(this).data('fSelect');
            if (!data) {
                data = new fSelect(this, settings);
                $(this).data('fSelect', data);
            }
            if (typeof settings == 'string') {
                data[settings]();
            }
        });
    }
    /**
     * Events
     */
    window.fSelect = {
        'active': null,
        'idx': -1
    };

    function setIndexes($wrap) {
        $wrap.find('.fs-option:not(.hidden)').each(function (i, el) {
            $(el).attr('data-index', i);
            $wrap.find('.fs-option').removeClass('hl');
        });
        $wrap.find('.fs-search input').focus();
        window.fSelect.idx = -1;
    }

    function setScroll($wrap) {
        var $container = $wrap.find('.fs-options');
        var $selected = $wrap.find('.fs-option.hl');
        var itemMin = $selected.offset().top + $container.scrollTop();
        var itemMax = itemMin + $selected.outerHeight();
        var containerMin = $container.offset().top + $container.scrollTop();
        var containerMax = containerMin + $container.outerHeight();
        if (itemMax > containerMax) { // scroll down
            var to = $container.scrollTop() + itemMax - containerMax;
            $container.scrollTop(to);
        } else if (itemMin < containerMin) { // scroll up
            var to = $container.scrollTop() - containerMin - itemMin;
            $container.scrollTop(to);
        }
    }

    $(document).on('click', '.fs-option', function () {
        var $wrap = $(this).closest('.fs-wrap');
        if ($wrap.hasClass('multiple')) {
            var selected = [];
            $(this).toggleClass('selected');
            $wrap.find('.fs-option.selected').each(function (i, el) {
                selected.push($(el).attr('data-value'));
            });
        } else {
            var selected = $(this).attr('data-value');
            $wrap.find('.fs-option').removeClass('selected');
            $(this).addClass('selected');
            $wrap.find('.fs-dropdown').addClass('hidden');
        }
        $wrap.find('select').val(selected);
        $wrap.find('select').fSelect('reloadDropdownLabel');
    });
    $(document).on('keyup', '.fs-search input', function (e) {
        if (40 == e.which) {
            $(this).blur();
            return;
        }
        var $wrap = $(this).closest('.fs-wrap');
        var keywords = $(this).val();
        var ret = /^[a-zA-Z]+$/;
        $wrap.find('.fs-option, .fs-optgroup-label').removeClass('hidden');
        if ('' != keywords) {
            $wrap.find('.fs-option').each(function () {
                var regex = new RegExp(keywords, 'gi');
                if (ret.test(keywords)) {
                    if (null === ($(this).find('.fs-option-label').text()).match(regex)) {
                        $(this).addClass('hidden');
                    }
                } else {
                    if (null === $(this).find('.fs-option-label').text().match(regex)) {
                        $(this).addClass('hidden');
                    }
                }
            });
            $wrap.find('.fs-optgroup-label').each(function () {
                var num_visible = $(this).closest('.fs-optgroup').find('.fs-option:not(.hidden)').length;
                if (num_visible < 1) {
                    $(this).addClass('hidden');
                }
            });
        }
        setIndexes($wrap);
    });
    $(document).on('click', function (e) {
        var $el = $(e.target);
        var $wrap = $el.closest('.fs-wrap');
        if (0 < $wrap.length) {
            if ($el.hasClass('fs-label')) {
                window.fSelect.active = $wrap;
                var is_hidden = $wrap.find('.fs-dropdown').hasClass('hidden');
                $('.fs-dropdown').addClass('hidden');
                if (is_hidden) {
                    $wrap.find('.fs-dropdown').removeClass('hidden');
                    //let h = $wrap.height() + 7;
                    let h = $wrap.height();
                    let offset = $wrap.offset();
                    $wrap.find(".fs-dropdown").offset({"top": offset.top + h, "left": offset.left});
                } else {
                    $wrap.find('.fs-dropdown').addClass('hidden');
                }
                setIndexes($wrap);
            }
        } else {
            $('.fs-dropdown').addClass('hidden');
            window.fSelect.active = null;
        }
    });
    $(document).on('keydown', function (e) {
        var $wrap = window.fSelect.active;
        if (null === $wrap) {
            return;
        } else if (38 == e.which) { // up
            e.preventDefault();
            $wrap.find('.fs-option').removeClass('hl');
            if (window.fSelect.idx > 0) {
                window.fSelect.idx--;
                $wrap.find('.fs-option[data-index=' + window.fSelect.idx + ']').addClass('hl');
                setScroll($wrap);
            } else {
                window.fSelect.idx = -1;
                $wrap.find('.fs-search input').focus();
            }
        } else if (40 == e.which) { // down
            e.preventDefault();
            var last_index = $wrap.find('.fs-option:last').attr('data-index');
            if (window.fSelect.idx < parseInt(last_index)) {
                window.fSelect.idx++;
                $wrap.find('.fs-option').removeClass('hl');
                $wrap.find('.fs-option[data-index=' + window.fSelect.idx + ']').addClass('hl');
                setScroll($wrap);
            }
        } else if (32 == e.which || 13 == e.which) { // space, enter
            $wrap.find('.fs-option.hl').click();
        } else if (27 == e.which) { // esc
            $('.fs-dropdown').addClass('hidden');
            window.fSelect.active = null;
        }
    });
})(jQuery);


// 提示框
(function () {
    "use strict";
    $.Toast = function (message, type, options) {
        let defaultOptions = {
            appendTo: "body",
            stack: false, // 堆叠显示
            positionClass: "toast-bottom-right",
            fullscreen: false,
            width: 250,
            spacing: 20,
            timeout: 4000,
            progress: false,
        }
        let $options = $.extend(true, {}, defaultOptions, options);
        let spacing = $options.spacing;
        let css = {
            "position": ($options.appendTo === "body") ? "fixed" : "absolute",
            "width": $options.width,
            "display": "none",
            "border-radius": '5px',
            "z-index": 99999
        }
        let ele = $(`<div class="toast-item-wrapper ${type} ${$options.positionClass}"></div>`);
        $(`<p class="toast-message">${message}</p>`).appendTo(ele);

        if ($options.fullscreen) {
            ele.addClass("fullscreen");
        }
        if ($options.progress && $options.timeout > 0) {
            $(`<div class="toast-progress"></div>`).appendTo(ele);
        }
        if ($options.stack) {
            if ($options.positionClass.indexOf("toast-top") !== -1) {
                $($options.appendTo).find('.toast-item-wrapper').each(function () {
                    css["top"] = parseInt($(this).css("top")) + this.offsetHeight + spacing;
                });
            } else if ($options.positionClass.indexOf("toast-bottom") !== -1) {
                $($options.appendTo).find('.toast-item-wrapper').each(function () {
                    css["bottom"] = parseInt($(this).css("bottom")) + this.offsetHeight + spacing;
                });
            }
        }
        ele.css(css);
        ele.appendTo($options.appendTo);
        if (ele.fadeIn) {
            ele.fadeIn();
        } else {
            $alert.css({
                display: 'block',
                opacity: 1
            });
        }

        function removeToast() {
            $.Toast.remove(ele);
        }

        if ($options.timeout > 0) {
            setTimeout(removeToast, $options.timeout);
            if ($options.progress) {
                $(".toast-progress", ele).animate({
                    "width": "100%"
                }, $options.timeout);
            }
        }
        return ele;
    }
    $.Toast.remove = function (ele) {
        if (ele.fadeOut) {
            ele.fadeOut(function () {
                return ele.remove();
            });
        } else {
            ele.remove();
        }
    }
})();


/**
 *
 * @param text 消息
 * @param type 类型 支持 info, success, error
 * @returns {*|jQuery|HTMLElement}
 */
function msg(text, type = 'info') {
    return $.Toast(text, type, {
        fullscreen: false,
        timeout: 4000,
        progress: true,
    });
}


jQuery.cookie = function (name, value, options) {
    if (typeof value != 'undefined') {
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString();
        }
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
}

function autoAdjustPosition($element){
    let height = $element.height();//元素本身高度
    let windowHeight = $(window).height(); // 获取窗口的可视区域高度
    let disHeight = windowHeight-height;
    let elementOffset = $element.offset().top;
    if (disHeight >0 && elementOffset>disHeight){
        let moveDistance = elementOffset-disHeight+2;
        // 移动元素
        $element.css('top', '-=' + moveDistance + 'px');
        // 获取计算后的样式对象
        $element.find(".arrow-ico").css('top', '+=' + moveDistance + 'px');
    }
}

/**
 * 显示第三和第四级菜单
 */
function showMenuFour(_this,menuOneName,menuTwoName){
    let element = $(".menu-four-box");
    element.find(".arrow-ico").css('top', '14px');
    let menuThree = $.grep(menuInit, function(item) {
        return (item.menuOneName === menuOneName && item.menuTwoName === menuTwoName);
    });
    let html = '';
    $.each(menuThree[0].children, function(index, item) {
        html += ` <div class="menu-four-box-col">
                    <div class="menu-four-title">${item.name}</div>
                    <div class="menu-four-content">`;
        $.each(item.children, function(index, secItem) {
            html += `<div class="menu-four-item" data-one="${menuOneName}" data-two="${menuTwoName}" data-three="${item.name}" iframehref="${secItem.iframeHref}" title="${secItem.name}" onclick="iframeHref(this)">${secItem.name}</div>`;
        });subForm
        html += `</div>
                </div>`;
    });
    $(".menu-four-box-inner").html(html);
    let offset = _this.offset();
    let h = _this.outerHeight();
    let scrollTop = $("#body").scrollTop();
    element.css({"top": scrollTop+offset.top + h - 38, "left": offset.left+128});
    element.show();
    $(".menu-four-back").show();
}

/**
 * 初始化菜单
 */
function initMenu(){
    $.post(root+'control/adIndex.html?cla=homepage&fun=getMenuJson',{},function (res) {
        menuInit = res.data;
    },'json')
}

/**
 * 隐藏四级菜单
 */
function hideMenuFour(){
    let element = $(".menu-four-box");
    element.find(".arrow-ico").css('top', '14px');
    element.hide();
    $(".menu-four-back").hide();
}

/**
 * 取消hover效果
 */
function removeHover() {
    //移出后，判断是否还在li[menutwo], .menu-four-box元素的内部，如果不是，则隐藏菜单且取消菜单高亮
    let item = $('.menu-four-box').find('.menu-four-item').eq(0);
    let iframeTitleNow = $('#iframeTitle .iframeTitleNow').children('[iframe_menu_two]');
    let one = item.data('one'),two=item.data('two');
    if (one !== iframeTitleNow.attr('iframe_menu_one') || two !== iframeTitleNow.attr('iframe_menu_two')){
        //当前菜单高亮和右边显示的页面不一致，取消菜单高亮
        $("[menu_one='"+one+"'][menutwo='"+two+"']").removeClass('frameLeftShow')
        $("[menu_one='"+iframeTitleNow.attr('iframe_menu_one')+"'][menutwo='"+iframeTitleNow.attr('iframe_menu_two')+"']").addClass('frameLeftShow')
    }
}

/**
 * 设置桌面快捷入口
 * @param e
 * @param page
 */
function setQuick(e,page){
    if (page){
        $.post(root+'control/adIndex.html?cla=homepage&fun=setQuickEntryEdit',{type:'add',quick:{"data":[page]}},function (res) {
            if (res.warn===2){
                if ($(e).hasClass('clip-selected')){
                    $(e).removeClass('clip-selected');
                    $(e).attr('title','设置桌面快捷入口');
                }else{
                    $(e).addClass('clip-selected');
                    $(e).attr('title','取消桌面快捷入口');
                }
                warn(res.msg)
            }
        },'json')
    }else{
        warn('未找到当前页面名称','error')
    }
}

//文件异步上传
function fileUpload(cla,fun,post){
    //参数准备
    var obj = $("#importFile")[0];//获取发生本次点击事件的元素对象
    if (!obj.files[0]){
        warn('请选择文件');
        return false
    }
    var fileSize = obj.files[0].size / 1024 / 1024;//文件大小MB
    //判断
    if(fileSize > 10){
        warn("上传文件的体积("+fileSize.toFixed(2)+"MB)不能超过10MB");
    }else{
        //进度条
        var progressBar = document.getElementById('progressBarId');
        //控件
        //var returnId = $(obj).attr("returnId");
        //var returnHtml = document.getElementById(returnId);
        //获取文件
        var formData = new FormData();
        //传递post参数
        if (post){
            post = JSON.parse(post);
            for(let key in post){
                formData.append(key,post[key]);
            }
        }
        //模板ID
        let form = $("form[name='importTemplateImportFrameForm']");
        let templateId = form.find("[name='templateId']:checked").val();
        formData.append("templateId",templateId);
        formData.append("file",obj.files[0]);
        //创建 XMLHttpRequest 对象
        var xhr = new XMLHttpRequest();
        //建立连接
        xhr.open("POST",root+"control/adIndex.html?cla="+cla+"&fun="+fun);
        $("#importButton").hide();
        //监听文件上传进度
        xhr.upload.onprogress = function(e){
            if(e.lengthComputable){
                //计算上传百分比
                var percent = Math.ceil(e.loaded/e.total*100);
                //如果是本函数自带进度条，则显示
                if($(progressBar).hasClass("progressBar")){
                    progressBar.style.display = "inline-block";
                }
                //利用背景显示进度样式
                progressBar.style.background = "linear-gradient(to right,#4c9cfb "+percent+"%,#fba489 "+percent+"%)";
            }
        }
        //接收返回的结果
        xhr.onreadystatechange = function(){//绑定响应状态事件监听函数
            if(xhr.readyState == 4 && xhr.status == 200){
                clearFileName();
                //隐藏进度条
                if($(progressBar).hasClass("progressBar")){
                    progressBar.style.display = "none";
                    $("#importButton").css('display','inline-block');
                }
                var data = JSON.parse(xhr.responseText);
                if(data.warn === 1){
                    //刷新页面
                    window.location.href = $("#renovate").attr("url");
                }else if(data.warn === 2){
                    templateDefault(templateId)
                    searchFormSub(cla,$("#importButton").data('fun'));
                    layer('importTemplate','importResultMessage',{title:data.data.title,text:data.data.text})
                    //弹窗显示导入日志
                    // window.location.href = $("#renovate").attr("url");
                }else{
                    warn(data.warn);
                }
            }
        }
        //发送请求
        xhr.send(formData);
    }
}

/**
 * 显示导入文件名称
 * @param e
 */
function setFileName(e) {
    $("form[name='importTemplateImportFrameForm'] .file-name").html($(e)[0].files[0].name)
}

/**
 * 清空导入文件
 */
function clearFileName() {
    $("form[name='importTemplateImportFrameForm'] .file-name").html('');
    $("form[name='importTemplateImportFrameForm'] #importFile").val('');
}
/**
 * 导入模板删除
 */
function templateDel(e,templateType=1) {
    var form = templateType == 1?$("#importTemplateAddImportTemplate form[name='templateForm']"):$("#importTemplateAddExportTemplate form[name='templateForm']");
    let id = form.find("[name='id']").val();
    $.post(root+'control/adIndex.html?cla=importTemplate&fun=templateDel',{id:id},function (res) {
        if (res.warn ===2){
            $('#importTemplateAddImportTemplate').hide();
            $('#importTemplateAddExportTemplate').hide()
            $("[name='templateId'][value='"+id+"']").parent().remove();
            $(".edit-icon[data-id='"+id+"']").remove();
            if (res.msg){
                warn(res.msg);
            }
        }else{
            msg(res.warn,'error')
        }
    },'json')
}

/**
 * 导入模板重置
 */
function templateReset(e,templateType=1) {
    var form = templateType == 1?$("#importTemplateAddImportTemplate form[name='templateForm']"):$("#importTemplateAddExportTemplate form[name='templateForm']");
    let page = form.find("[name='page']").val();
    $.post(root+'control/adIndex.html?cla=importTemplate&fun=templateReset',{page:page,templateType:templateType},function (res) {
        if (res.warn ===2){
            form.find(".body").empty().append(res.html);
            if (res.msg){
                warn(res.msg);
            }
        }else{
            msg(res.warn,'error')
        }
    },'json')
}

/**
 * 导入导出模板重置默认
 */
function templateDefault(templateId='') {
    if(templateId) {
        $.post(root + 'control/adIndex.html?cla=importTemplate&fun=templateDefault', {
            templateId: templateId
        }, function (res) {

        }, 'json')
    }
}


/**
 * 导入模板保存
 */
function templateConfirm(e,templateType=1) {
    var form = templateType == 1?$("#importTemplateAddImportTemplate form[name='templateForm']"):$("#importTemplateAddExportTemplate form[name='templateForm']");
    let id = form.find("[name='id']").val();
    let page = form.find("[name='page']").val();
    let classify = form.find("[name='classify']").val();
    //参数准备
    var templateName = form.find("[name='templateName']").val();
    //列名称
    var install = {};
    form.find("[name='columnId\[\]']").each(function(){
        var name = $(this).val();
        let  display = 0;
        if($(this).prop("checked")){
            display = 1;
        }
            install[name] = {
                "display":display,
                "columnName":$(this).parents("ul").children(":eq(1)").children("input[name='columnName']").val(),
                "aliasName":$(this).parents("ul").children(":eq(2)").children("input[name='aliasName']").val(),
                "list":$(this).parents("ul").children(":eq(3)").children("input[name='list']").val(),
            }
    });
    //整理json数组
    let postData = {
        "page":page,
        "id":id,
        "templateName":templateName,
        "classify":classify,
        "templateType":templateType,
        "install":install
    };
    //请求服务器
    $.post(root+"control/adIndex.html?cla=importTemplate&fun=templateConfirm",postData,function(data){
        if(data.warn === 2){
            $('#importTemplateAddImportTemplate').hide();
            $('#importTemplateAddExportTemplate').hide();
            if (templateType == 1){
                $("#importTemplateImportFrame #template-option").html(data.html);
            }else{
                $("#importTemplateExportFrame #template-option").html(data.html);
            }

            if (data.msg){
                warn(data.msg);
            }
        }else{
            warn(data.warn);
        }
    },"json");
}

/**
 * 导入和导出模板编辑
 */
function templateEdit(page,cla,classify,id,templateType) {
    if (templateType==1)
        layer(page,'addImportTemplate',{cla:cla,classify:classify,id:id})
    else
        layer(page,'addExportTemplate',{cla:cla,classify:classify,id:id})
}
/******模板字段权限框是否选中*****/
function templateBoxChange(){
    //参数准备
    var form = $(event.target).parents("form");
    let name = form.attr('name');
    //全选框状态设定
    if(form.find("[name='columnId\[\]']").length == form.find("[name='columnId\[\]']:checked").length){
        form.find("input[form='"+name+"']").prop('checked',true);
    }else{
        form.find("input[form='"+name+"']").prop('checked',false);
    }
}

/***模板字段全选***/
function templatecheckAll(obj) {
    var formName = $(obj).attr("form");
    var checkName = $(obj).attr("name");
    var form = $(obj).closest("[name='"+formName+"']");
    var bool = $(obj).prop("checked");
    form.find("[name='" + checkName + "\\[\\]']:not([disabled])").prop('checked', bool);
}

/**
 * 下载导入模板
 * @param cla
 * @param fun
 * @param attach
 */
function downloadImportTemplate(cla,fun, postData) {
    let data = '';
    postData =JSON.parse(postData);
    $.each(postData, function(key, value) {
        data+="&"+key+"="+value;
    });
    var form = $("form[name='importTemplateImportFrameForm']");
    let templateId = form.find("[name='templateId']:checked").val();
    window.location = root+"control/adIndex.html?cla="+cla+"&fun="+fun+"&templateId="+templateId+data;
}

/**
 * 下载导出模板
 */
function exportFileDownload(cla,fun,checkbox,postData) {
    let data = '';
    postData =JSON.parse(postData);
    $.each(postData, function(key, value) {
        data+="&"+key+"="+value;
    });
    //获取勾选的ID
    let checkedId = [];
    $("input[name='"+checkbox+"']:checked").each(function () {
        checkedId.push($(this).val())
    })
    //模板ID
    let form = $("form[name='importTemplateExportFrameForm']");
    let templateId = form.find("[name='templateId']:checked").val();
    // if (!templateId){
    //     msg("请先选择模板","error");
    //     return;
    // }
    data+="&templateId="+templateId+"&checkedId="+checkedId.join(",");
    location.href = root+"control/adIndex.html?cla="+cla+"&fun="+fun+data;
}

function objectToFormData(obj) {
    return Object.keys(obj)
        .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`)
        .join('&');
}

function fetchData(url = '', data = {}, callback) {
    return fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: objectToFormData(data)
    })
        .then(response => response.json().catch(() => Promise.reject('非json 格式')))
        .then(res => {
            if (res.warn === 2) {
                window.location.reload()
            } else {
                if (typeof callback === 'function') {
                    const callbackName = callback.name;
                    if (callbackName === 'warn' || callbackName === 'msg') {
                        callback(res.warn)
                    } else {
                        callback(res)
                    }
                }
            }
        })
        .catch(error => console.error('Error:', error));
}
